"""
Case Type   : 故障&可靠性测试
Case Name   : 闰年跨年时恢复数据
Create At   : 2020/11/25
Owner       : @zou_jialiang0505328126
Description :
    1.设置主节点为2019-12-31 23:59:40（2020年为闰年）
    2.使用gs_restore恢复数据
    3.检查数据一致性
    4.执行tpcc
    5.检查数据一致性
Expect      :
    1.设置成功
    2.恢复成功
    3.数据一致
    4.执行tpcc成功
    5.数据一致
History     :
    modified: 2020/03/01  modified by @peilinqian,修改创建数据库SQL；以防已存在库导致断言失败
        修改生成预设数据命令导致的失败
    modified: 2020/12/11  modified by @wan005,修改恢复数据库为新创建数据库，防止恢复失败导致后续用例失败
    modified: 2021/01/08  modified by @wan005,物化视图不支持compression等参数，修改断言适配1.1.0版本
    Modified by @wan005 2021/1/22: 增加ntp服务安装步骤
    Modified by @wan005 2021/3/23: 增加环境时区修复步骤
    Modified by @wan005 2021/11/22: 增加tpcc result删除步骤，规避tpcc失败问题
"""

import os
import unittest
import sys
from yat.test import macro
from yat.test import Node

sys.path.append(sys.path[0] + "/../")
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Basebackup(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    commonshsta = CommonSH('Standby1DbUser')
    commonshsta2 = CommonSH('Standby2DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Tools_Restore_Case011.py 开始执行------------')
        self.dbPrimaryDbUser = Node(node='PrimaryDbUser')
        self.dbStandby1DbUser = Node(node='Standby1DbUser')
        self.dbStandby2DbUser = Node(node='Standby2DbUser')
        self.dbStandby1Root = Node(node='Standby1Root')
        self.db_primary_root_node = Node(node='PrimaryRoot')
        self.Constant = Constant()
        self.common = Common('PrimaryRoot')
        self.restore_file = os.path.join(macro.DB_BACKUP_PATH, 'dump_backup', 'tools_restore_case001.tar')
        self.sql_path = os.path.join(macro.DB_BACKUP_PATH, 'testscript')

        result = self.common.check_system_timezone(
            *('PrimaryRoot', 'Standby1Root', 'Standby2Root'))
        self.log.info(result)
        self.assertTrue(result)

        self.log.info('=====安装ntp服务=======')
        result = self.db_primary_root_node.sh('yum install -y ntp').result()
        self.log.info(result)
        result = self.db_primary_root_node.sh(
            'systemctl enable ntpd').result()
        self.log.info(result)
        result = self.db_primary_root_node.sh('systemctl start ntpd').result()
        self.log.info(result)

        self.log.info('-------------------创建备份路径-----------------------------------')
        shell_cmd = f'rm -rf {os.path.dirname(self.restore_file)}; mkdir {os.path.dirname(self.restore_file)}'
        self.log.info(shell_cmd)
        result = self.dbPrimaryDbUser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('-----------------------生成预设数据-----------------------')
        result = self.common.scp_file(self.dbPrimaryDbUser, 'restore_data.sql', self.sql_path)
        self.log.info(result)
        sql_file = os.path.join(self.sql_path, 'restore_data.sql')
        sql_file_cmd = f'source {macro.DB_ENV_PATH}; ' \
            f'gsql -d {self.dbPrimaryDbUser.db_name} ' \
            f'-p {self.dbPrimaryDbUser.db_port} ' \
            f'-f {sql_file}'
        self.log.info(sql_file_cmd)
        sql_bx_msg = self.dbPrimaryDbUser.sh(sql_file_cmd).result()
        self.log.info(sql_bx_msg)
        self.assertNotIn('ERROR', sql_bx_msg)

        self.log.info('--------------------获取还原前数据库已有表------------------------')
        self.table_list = self.commonshpri.executDbSql(r'\d')
        self.log.info(self.table_list)

        self.log.info('--------------------导出数据----------------------------')
        result = self.commonshpri.dumpFile(filename=self.restore_file, get_detail=False)
        self.log.info(result)
        self.assertTrue(result)

        self.dbname = 'dbsys_restore_db'
        self.log.info("---------------------创建数据库--------------------")
        create_db_sql = f'drop database if exists {self.dbname};' \
            f'create database {self.dbname};'
        result = self.commonshpri.executDbSql(create_db_sql)
        self.log.info(result)
        self.assertIn(self.Constant.CREATE_DATABASE_SUCCESS_MSG, result)

    def test_basebackup(self):
        self.log.info("-----------设置操作系统时间为12/31/2019 23:59:40--------------------")
        datecmd = "date -s '12/31/2019 23:59:40';hwclock --systohc;" \
                  "service ntpd stop;ntpdate ntp.api.bz;service ntpd start"
        self.log.info(datecmd)
        self.log.info(self.db_primary_root_node.sh(datecmd).result())
        before_time = self.commonshpri.executDbSql('select now();')
        self.log.info(before_time)
        self.assertTrue("2019-12-31" in before_time or
                        "2020-01-01" in before_time)

        self.log.info('-------------------恢复数据-----------------------------------')
        result = self.commonshpri.restoreFile(self.restore_file, get_detail=True, dbname=self.dbname)
        self.assertIn(self.Constant.RESTORE_SUCCESS_MSG, result)

        self.log.info('-------------------查看数据库当前时间-----------------------------------')
        afterTime = self.commonshpri.executDbSql('select now();')
        self.log.info(afterTime)
        self.assertIn("2020-01-01", afterTime)

        self.log.info('-------------------检查主备是否同步-------------------')
        result = self.commonshsta.check_data_consistency()
        self.assertTrue(result)
        result = self.commonshsta2.check_data_consistency()
        self.assertTrue(result)

        self.log.info('--------------------检查数据一致性---------------------')
        nodes_tuple = (self.dbPrimaryDbUser, self.dbStandby1DbUser, self.dbStandby2DbUser)
        flag = self.common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.common.format_sql_result(self.commonshpri.executDbSql(r'\d', dbname=self.dbname))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.common.check_data_sample_by_all(select_sql, *nodes_tuple)
            self.assertTrue(flag)

        self.log.info('------------------启动TPCC----------------------------')
        cmd = f"rm -rf " \
            f"{os.path.join(macro.TPCC_PATH, 'my_result_2020-01-01*')}"
        self.log.info(cmd)
        result = self.db_primary_root_node.sh(cmd).result()
        self.log.info(result)
        result = self.common.startTPCC(self.db_primary_root_node, macro.TPCC_PATH)
        self.log.info(result)
        self.assertIn(self.Constant.TPCC_SUCCESS_MSG, result)

        self.log.info('-------------------检查主备是否同步-------------------')
        result = self.commonshsta.check_data_consistency()
        self.assertTrue(result)
        result = self.commonshsta2.check_data_consistency()
        self.assertTrue(result)

        self.log.info('--------------------检查数据一致性---------------------')
        nodes_tuple = (self.dbPrimaryDbUser, self.dbStandby1DbUser, self.dbStandby2DbUser)
        flag = self.common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.common.format_sql_result(self.commonshpri.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.common.check_data_sample_by_all(select_sql, *nodes_tuple)
            self.assertTrue(flag)

    def tearDown(self):
        self.log.info('-------------------------环境清理------------------------')
        self.log.info('--------------------------删除备份文件------------------')
        shell_cmd = f'rm -rf {os.path.dirname(self.restore_file)}'
        self.log.info(shell_cmd)
        result = self.dbPrimaryDbUser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('--------------------------删除预设数据---------------------')
        result = self.common.scp_file(self.dbPrimaryDbUser, 'clear_restore_data.sql', self.sql_path)
        self.log.info(result)
        clean_sql_file = os.path.join(self.sql_path, 'clear_restore_data.sql')
        sql_file_cmd = f'source {macro.DB_ENV_PATH};' \
            f'gsql -d {self.dbPrimaryDbUser.db_name} ' \
            f'-p {self.dbPrimaryDbUser.db_port} ' \
            f'-f {clean_sql_file}'
        self.log.info(sql_file_cmd)
        sql_bx_msg = self.dbPrimaryDbUser.sh(sql_file_cmd).result()
        self.log.info(sql_bx_msg)

        self.log.info('----------------------删除执行脚本路径----------------------------')
        shell_cmd = f'rm -rf {self.sql_path}'
        self.log.info(shell_cmd)
        result = self.dbPrimaryDbUser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info("---------------------恢复系统时间-------------------------")
        current = self.dbStandby1Root.sh("date \"+%m/%d/%Y %H:%M:%S\"").result()
        self.log.info(current)

        datecmd = f'date -s "{current}"'
        result = self.db_primary_root_node.sh(datecmd).result()
        self.log.info(datecmd)
        self.log.info(result)

        datecmd = 'hwclock --systohc;service ntpd stop;ntpdate ntp.api.bz;service ntpd start '
        result = self.db_primary_root_node.sh(datecmd).result()
        self.log.info(datecmd)
        self.log.info(result)

        self.log.info("---------------------drop database--------------------")
        result = self.commonshpri.executDbSql(f'drop database {self.dbname};')
        self.log.info(result)
        self.log.info('----------Opengauss_Reliability_Tools_Restore_Case011.py 执行结束-----------------------')
